<?php

namespace App\Http\Middleware;

use App\Config\AuthConfig;
use App\Enum\APIEnum;
use App\Exceptions\APIHttpException;
use App\Http\Model\Auth\AuthModel;
use App\Http\Service\Auth\LoginService;
use Closure;

class Auth
{

    /*员工登录信息*/
    private static $user = [];

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure                 $next
     *
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        /*检查系统是否正在维护中*/
        if (config('ext.is_maintain') === true) {
            throw new APIHttpException('系统维护中...');
        }
        /*白名单请求过滤*/
        if (!in_array(request()->path(), AuthConfig::LOGIN_NOT_VERIFY)) {
            /*鉴权*/
            $this->verify();
        }
        return $next($request);
    }


    /**
     * 获取有权限的监管账户ID
     * demo:    Auth::pfs([2],0);
     *
     * @param array  $enumId    业务线ID,默认不限制业务线
     * @param string $default   如果没有任何监管账户权限时,默认返回的值
     *
     * @return array|mixed|string
     */
    public static function pfs(array $enumId = [], $default = '')
    {
        $pfsId = self::user('pfs_dw_id');
        if (empty($enumId) || empty($pfsId)) {
            return empty($pfsId) ? $default : $pfsId;
        }
        /*如果是查下指定业务线的权限*/
        $pfsId = AuthModel::pfsId($enumId, $pfsId);
        return empty($pfsId) ? $default : $pfsId;
    }


    /**
     * 获取登录信息
     *
     * @param string|null $field
     *
     * @return array|mixed|null
     */
    public static function user(string $field = null)
    {
        if (empty($field)) {
            return self::$user;
        }
        return isset(self::$user[$field]) ? self::$user[$field] : null;
    }


    /**
     * 鉴权
     */
    private function verify()
    {
        $token = request()->header('Token');
        if (empty($token)) {
            throw new APIHttpException('请登录', APIEnum::LOGIN_VOID['code']);
        }
        /*获取指定token对应登录信息*/
        self::$user = LoginService::token($token);
    }
}
